export default function syncToken(token: string, uid: string, withRootPath: boolean = false, timeout = 3000) {

    return (targetUrl: string) => {
        // 这里需要判断是否同源，暂直接判断url是否合法
        if(!token || token === '' || !$validUrl(targetUrl)) {
            return new Promise((resolve) => {
                resolve('')
            })
        }
        return new Promise((resolve) => {
            const message = {
                type: 'synchronizationToken',
                token: token,
                uid: uid
            }

            let frame = document.createElement('iframe')
            frame.style.position = 'absolute';
            frame.style.top = '-9999px';
            frame.style.left = '-9999px';
            frame.style.width = '1px';
            frame.style.height = '1px';
            frame.name = 'syncTokenFrame' + new Date().getTime()

            // 超时不做任何处理
            let timer = setTimeout(() => {
                resolve('timeout')
            }, timeout);
            const parentHandleMessage = (event: MessageEvent) => {
                try {
                    const data = JSON.parse(event.data)
                    if (data.type === 'synchronizationToken') {
                        document.body.removeChild(frame);
                        window.removeEventListener('message', parentHandleMessage)
                        clearTimeout(timer)
                        resolve(data.value)
                    }
                } catch (e) {
                    console.error(e)
                }
            }

            window.addEventListener('message', parentHandleMessage)

            let child: Window | null = null;
            frame.onerror = (event) => {
                console.log('error', event)
            }
            frame.onload = (e) => {
                child = frame.contentWindow
                setTimeout(() => {
                    child?.postMessage(JSON.stringify(message), new URL(targetUrl).origin);
                })
            }

            let u = new URL(targetUrl)
            let p = u.pathname.substring(1)
            let path = p.substring(0, p.indexOf('/'))
            if(path === '' || !withRootPath) {
                frame.setAttribute('src', new URL(targetUrl).origin + '/synchronizationToken.html');
            } else {
                frame.setAttribute('src', new URL(targetUrl).origin + '/' + path + '/synchronizationToken.html');
            }
            document.body.appendChild(frame);
        })
    }
}
/**
 * URL地址校验
 * @param {String} url
 * @returns {Boolean}
 */
function $validUrl(url: string) {
    const reg =
        /^(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?$/;
    return reg.test(url);
}
